from grafana_api_plugin import grafana_lib
import time
import datetime
from notify import send_email


grafana_url = 'http://192.168.1.1:3000'
token = 'adfwoiuqwelkzvn,xz12124-124809124lkdslksn,safndsaf'
grafana_server = grafana_lib(grafana_url, token)
datasource_id = 1

group = [
    {'job': '测试服务器群组监控', 'instance': '192.168.1.250:9100'}
]

# 1.先调用grafana的api获取服务器磁盘分区的相关数据
def get_server_disk_info(job, instance):
    # 01.这个查询语句的意思是查找对应服务器的磁盘分区信息, 和磁盘分区的空间大小, 容量使用byte表示
    promql01 = '''
    node_filesystem_size_bytes{job=~'%s', instance=~'%s', fstype!~"tmpfs|rootfs", mountpoint !~ ".*pod.*"} - 0
    ''' % (job, instance)
    res01 = grafana_server.query_grafana(datasource_id, promql01)
    server_disk_info_list = res01['data']['result']

    l1 = []
    for server_disk_info in server_disk_info_list:
        d1 = {}
        d1['device'] = server_disk_info['metric']['device']
        d1['fstype'] = server_disk_info['metric']['fstype']
        d1['instance'] = server_disk_info['metric']['instance']
        d1['job'] = server_disk_info['metric']['job']
        d1['mountpoint'] = server_disk_info['metric']['mountpoint']
        d1['time'] = server_disk_info['value'][0]
        d1['total_size_byte'] = int(server_disk_info['value'][1])
        l1.append(d1)

    # 02.获取服务器磁盘剩余容量
    promql02 = '''
    node_filesystem_avail_bytes{job=~'%s', instance=~'%s', fstype !~ "tmpfs|rootfs", mountpoint !~ ".*pod.*"} - 0
    ''' % (job, instance)
    res02 = grafana_server.query_grafana(datasource_id, promql02)
    server_disk_avail_data = res02['data']['result']

    for i in l1:
        for avail_data in server_disk_avail_data:
            if i['instance'] == avail_data['metric']['instance'] and i['device'] == avail_data['metric']['device']:
                i['avail_size_byte'] = int(avail_data['value'][1])

    # 03.获取服务器磁盘使用率百分比
    promql03 = '''
    (node_filesystem_size_bytes{job=~'%s', instance=~'%s', fstype !~ "tmpfs|rootfs", mountpoint !~ ".*pod.*"}
    -node_filesystem_free_bytes{job=~'%s', instance=~'%s', fstype !~ "tmpfs|rootfs", mountpoint !~ ".*pod.*"}) * 100 
    /(node_file_system_avail_bytes{job=~'%s', instance=~'%s', fstype !~ "tmpfs|rootfs", mountpoint !~ ".*pod.*"})
    +(node_file_system_size_bytes{job=~'%s', instance=~'%s', fstype !~ "tmpfs|rootfs", mountpoint !~ ".*pod.*"}
    -(node_file_system_free_bytes{job=~'%s', instance=~'%s', fstype !~ "tmpfs|rootfs", mountpoint !~ ".*pod.*"}))
    ''' % (job, instance, job, instance, job, instance, job, instance, job, instance)
    res03 = grafana_server.query_grafana(datasource_id, promql03)
    server_disk_usage_percent = res03['data']['result']

    for i in l1:
        for disk_usage_percent in server_disk_usage_percent:
            if i['instance'] == disk_usage_percent['metric']['instance'] and i['device'] == disk_usage_percent['metric']['device']
                i['disk_usage_percent'] = disk_usage_percent['value'][1]


    # 04.计算出磁盘已经使用的容量
    for i in l1:
        i['use_size_bytes'] = i['total_size_bytes'] - i['avail_size_bytes']

    # print(l1)
    return l1


def content_auto_generate(content, group):
    for host_info in group:
        data = get_server_disk_info(host_info['job'], host_info['instance'])
        print(data)

        for disk_data in data:
            if disk_data['mountpoint'] == '/app':
                instance = disk_data['instance']
                percent = round(disk_data['disk_usage_percent'], 2)
                total = round(disk_data['total_size_bytes'] / 1024 / 1024 / 1024, 1)
                use = round(disk_data['use_size_bytes'] / 1024 / 1024 / 1024, 1)
                avail = round(disk_data['avail_size_bytes'] / 1024 / 1024 / 1024, 1)

                # 巡检报告生成
                message = """机器名称：%s, app目录磁盘空间使用率：%s, 目录总大小：%sG, 目录使用：%sG, 剩余：%sG\t\n""" % (instance, str(percent) + '%', total, use, avail)
                content = content + message
                break

    return content



if __name__ == '__main__':

    current_datetime = datetime.datetime.now()
    formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
    email_title = formatted_datetime + ' - 自动化巡检任务 - 磁盘巡检'

    service_content = '''
    nginx、tomcat、gitlab巡检完成
    '''

    elasticsearch_content = '''
    elasticsearch集群巡检完成
    '''

    end_content = '''
    该邮件通过自动化巡检脚本生成发送, 请勿回复此邮件, 如有疑问, 烦请电话联系
    '''


    service_content = content_auto_generate(service_content, group)
    elasticsearch_content = content_auto_generate(elasticsearch_content, group)

    content = ''
    content = content + service_content.replace(' ', '') + '\n'
    content = content + elasticsearch_content.replace(' ', '') + '\n'
    content = content + end_content.replace(' ', '') + '\n'
    print(content)

    # 发送日常巡检结果邮件给对应的用户
    # send_email('test@163.com', email_title, content)